﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;

namespace Limiting
{
    public class LimitingOptions
    {
        public LimitingOptions()
        {
            //给一个配置默认值
            Limit = 10;
            Time = TimeSpan.FromSeconds(60);
            Allows = Array.Empty<string>();
            CallbackDelegate = new(async ctx =>
            {
                ctx.Response.StatusCode = 503;
                ctx.Response.ContentType = "application/json;charset=utf-8";
                var json = "{\"message\":\"访问太快了，休息一下吧\"}";
                await ctx.Response.WriteAsync(json);
            });
            IdentityDelegate = new(ctx =>
            {
                return ctx.Request.HttpContext
                    .Connection.RemoteIpAddress.MapToIPv4().ToString();
            });
        }
        /// <summary> 约定次数 </summary>
        public int Limit { get; set; }
        /// <summary> 约定时间 </summary>
        public TimeSpan Time { get; set; }
        /// <summary> 白名单 </summary>
        public IEnumerable<string> Allows { get; set; }
        
        public Action<HttpContext> CallbackDelegate { get; set; }
        /// <summary> 设置限流的键 </summary>
        public Func<HttpContext, string> IdentityDelegate { get; set; }
    }
}
